package com.haiya.identityaccess.infrastructure.persistence.mybatis.repository;

import com.haiya.identityaccess.domain.access.model.Role;
import com.haiya.identityaccess.domain.access.repository.RoleRepository;
import com.haiya.identityaccess.domain.identity.model.TenantId;
import com.haiya.identityaccess.infrastructure.persistence.mybatis.datamodel.DataRole;
import com.haiya.identityaccess.infrastructure.persistence.mybatis.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author qiaoguoqiang
 */
@Repository
public class RoleRepositoryImpl implements RoleRepository {
    @Autowired
    RoleMapper roleMapper;

    @Override
    public void add(Role aRole) {
        DataRole dataRole = new DataRole(
                aRole.tenantId().id(),
                aRole.name(),
                aRole.description());
        roleMapper.insert(dataRole);
    }

    @Override
    public Collection<Role> allRoles(TenantId aTenantId) {
        List<DataRole> dataRoles = roleMapper.allRoles(aTenantId.id());
        Collection<Role> roles = new ArrayList<>();
        for (DataRole dataRole : dataRoles) {
            roles.add(new Role(aTenantId, dataRole.getName(), dataRole.getDescription()));
        }
        return roles;
    }

    @Override
    public void remove(Role aRole) {
        roleMapper.removeNamed(aRole.tenantId().id(), aRole.name());
    }

    @Override
    public Role roleNamed(TenantId aTenantId, String aRoleName) {
        DataRole dataRole = roleMapper.roleNamed(aTenantId.id(), aRoleName);
        return new Role(aTenantId, dataRole.getName(), dataRole.getDescription());
    }
}
